package com.haoshuang.zhouzhoubang.ui.page.order.time

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.haoshuang.zhouzhoubang.databinding.ActivityUpdateServiceTimeBinding
import com.haoshuang.zhouzhoubang.model.bean.RlBean2
import com.haoshuang.zhouzhoubang.model.bean.TimeBean2
import com.haoshuang.zhouzhoubang.model.bean.TimeBean99
import com.haoshuang.zhouzhoubang.utils.ListSplitUtils
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Calendar
import java.util.Date

/**
 *  修改上门时间
 */
class UpdateServiceTimeActivity :
    BaseVMActivity<UpdateServiceTimeViewModel, ActivityUpdateServiceTimeBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<UpdateServiceTimeActivity>()
        }
    }

    // 二级分类id
    private val cate_id by lazy { intent.getString("cate_id") }

    // 是不是门店订单
    private val is_team by lazy { intent.getString("is_team", "0") }

    private var list = arrayListOf<TimeBean99>()
    private var list200 = arrayListOf<TimeBean2>()
    private lateinit var adapter: TimeAllAdapter
    private var service_day = ""
    private var service_time = ""

    override fun initView(savedInstanceState: Bundle?) {
        binding.titleBar.title = "修改上门时间"
        binding.titleBar.leftImageView().click { finish() }
        binding.apply {
            adapter=TimeAllAdapter(list, is_team)
            tvCommit.clickWithTrigger {
                if (service_time.isNullOrBlank()) {
                    toast("请选中时间在提交")
                    return@clickWithTrigger
                }
                var time = timeStrToSecond(service_day) / 1000
                intent.putExtra("service_day", time.toString())
                intent.putExtra("service_day1", service_day)
                intent.putExtra("service_time", service_time)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }

            rvList.layoutManager = LinearLayoutManager(mActivity)
            rvList.adapter = adapter

        }
    }


    override fun initData() {
        readWorldAreaCode()
    }

    override fun startObserve() {
        vm.getMasterServiceTimeData.observeState(this){
            onError { code, msg ->
                toast(msg)
            }
            onSuccess {
                list200.clear()
                val curDate = Date(System.currentTimeMillis())
                var  tie90 = getTime22(curDate)
                var arr = tie90.split(" ")
                var arr2=arr[1].split(":")

                var num2 = setINt(arr2[0]) // 小时
                var num3 = setINt(arr2[1]) // 分钟

                list200.addAll(it?.data?: mutableListOf())
                if (isJt==0){
                    for (b in list200){
                        var arr=b.service_time.split("-")
                        var arr2 = arr[1].split(":")
                        var num = setINt(arr2[0])
                        var num1 = setINt(arr2[1])

                        if (num < num2) {
                            b.isCheck = 2
                        } else if (num == num2 && num1 <= num3){
                            b.isCheck = 2
                        }
                    }
                }
                list[layoutPosition2].isCheck=1
                adapter.notifyDataSetChanged()
            }
        }
    }

    private fun getTime2(date: Date): String {//可根据需要自行截取数据显示
        val format = SimpleDateFormat("yyyy-MM-dd")
        return format.format(date)
    }

    private fun getTime22(date: Date): String {//可根据需要自行截取数据显示
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        return format.format(date)
    }

    fun timeStrToSecond(time: String): Long {
        try {
            val format =
                SimpleDateFormat("yyyy-MM-dd")
            return format.parse(time).time
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return -1L
    }

    private fun readWorldAreaCode() {
        var time8 = 60
        val curDate = Date(System.currentTimeMillis())
        var tie90 = getTime2(curDate)
        var arr = tie90.split("-")
        var year = arr[0]
        var month = arr[1]
        var day9 = arr[2]
        var year2 = ""
        var month2 = ""
        var month3 = ""
        var year3 = ""
        if (setINt(month) < 12) {
            year2 = year
            var num2 = setINt(month) + 1
            month2 = setINt2(num2)
            if (num2 < 12) {
                year3 = year
                var num3 = num2 + 1
                month3 = setINt2(num3)
            } else {
                var num = year2.toInt() + 1
                year3 = num.toString()
                month3 = "01"
            }

        } else {
            var num = year.toInt() + 1
            year2 = num.toString()
            month2 = "01"
            year3 = num.toString()
            month3 = "02"
        }
        var oneNian = getMonthOfDay(year.toInt(), setINt(month))
        var twoNian = getMonthOfDay(year2.toInt(), setINt(month2))
        //  var threeNian=getMonthOfDay(year3.toInt(),setINt(month3))
        var timeOne = oneNian - setINt(day9)
        var list2 = arrayListOf<RlBean2>()
        var list3 = arrayListOf<RlBean2>()
        var list4 = arrayListOf<RlBean2>()
        var zhouj = getFirstDayWeek2(year.toInt(), setINt(month), setINt(day9))
        var zhouj2 = getFirstDayWeek(year2.toInt(), setINt(month2))
        var zhouj3 = getFirstDayWeek(year3.toInt(), setINt(month3))
        //日：1      一：2     二：3     三：4     四：5     五：6     六：7
        setList(zhouj, list2, year, month)
        for (b in 1..oneNian) {
            if (b >= setINt(day9)) {
                list2.add(RlBean2(year, month, b.toString()))
            }
        }
        var jih = ListSplitUtils.splitList(list2, 7)
        for (b in jih.indices) {
            try {
                var list9 = arrayListOf<RlBean2>()
                list9.addAll(jih[b])
                if (b == 0) {
                    list.add(TimeBean99("${year}年${month}月", 0, 1, list9, list200))
                } else {
                    list.add(TimeBean99("${year}年${month}月", 0, 0, list9, list200))
                }
            } catch (e: Exception) {

            }


        }
        var sheng = time8 - timeOne
        setList(zhouj2, list3, year2, month2)
        setList(zhouj3, list4, year3, month3)
        if (sheng > twoNian) {
            for (b in 1..twoNian) {
                list3.add(RlBean2(year2, month2, b.toString()))
            }
            var jih2 = ListSplitUtils.splitList(list3, 7)
            for (b in jih2.indices) {
                try {
                    var list9 = arrayListOf<RlBean2>()
                    list9.addAll(jih2[b])
                    if (b == 0) {
                        list.add(TimeBean99("${year2}年${month2}月", 0, 1, list9, list200))
                    } else {
                        list.add(TimeBean99("${year2}年${month2}月", 0, 0, list9, list200))
                    }
                } catch (e: Exception) {

                }

            }
            var shen2 = sheng - twoNian
            for (b in 1..shen2) {
                list4.add(RlBean2(year3, month3, b.toString()))
            }
            var jih3 = ListSplitUtils.splitList(list3, 7)
            for (b in jih3.indices) {
                try {
                    var list9 = arrayListOf<RlBean2>()
                    list9.addAll(jih3[b])
                    if (b == 0) {
                        list.add(TimeBean99("${year3}年${month3}月", 0, 1, list9, list200))
                    } else {
                        list.add(TimeBean99("${year3}年${month3}月", 0, 0, list9, list200))
                    }
                } catch (e: Exception) {

                }

            }
        } else {
            for (b in 1..sheng) {
                list3.add(RlBean2(year2, month2, b.toString()))
            }
            var jih2 = ListSplitUtils.splitList(list3, 7)
            for (b in jih2.indices) {
                try {
                    var list9 = arrayListOf<RlBean2>()
                    list9.addAll(jih2[b])
                    if (b == 0) {
                        list.add(TimeBean99("${year2}年${month2}月", 0, 1, list9, list200))
                    } else {
                        list.add(TimeBean99("${year2}年${month2}月", 0, 0, list9, list200))
                    }
                } catch (e: Exception) {

                }

            }
        }
        adapter.notifyDataSetChanged()
    }

    private fun setList(
        zhouj2: Int,
        list3: ArrayList<RlBean2>,
        year: String,
        month: String
    ) {
        when (zhouj2) {

            2 -> {
                list3.add(RlBean2(year, month, "0"))
            }

            3 -> {
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
            }

            4 -> {
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
            }

            5 -> {
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))

            }

            6 -> {
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
            }

            7 -> {
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
                list3.add(RlBean2(year, month, "0"))
            }
        }
    }

    fun getMonthOfDay(year: Int, month: Int): Int {
        var day = 0
        day = if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            29
        } else {
            28
        }
        when (month) {
            1, 3, 5, 7, 8, 10, 12 -> return 31
            4, 6, 9, 11 -> return 30
            2 -> return day
        }
        return 0
    }

    /**
     * 返回当前月份1号位于周几
     *
     * @param year  年份
     * @param month 月份，传入系统获取的，不需要正常的
     * @return 日：1      一：2     二：3     三：4     四：5     五：6     六：7
     */
    fun getFirstDayWeek(year: Int, month: Int): Int {

        val calendar: Calendar = Calendar.getInstance()
        //设置某一年
        calendar.set(year, month - 1, 1)
        var week = calendar.get(Calendar.DAY_OF_WEEK)

        return week

    }

    fun getFirstDayWeek2(year: Int, month: Int, day: Int): Int {

        val calendar: Calendar = Calendar.getInstance()
        //设置某一年
        calendar.set(year, month - 1, day)
        var week = calendar.get(Calendar.DAY_OF_WEEK)

        return week

    }

    private fun setINt(month: String): Int {
        var str1 = 0
        when (month) {
            "01" -> {
                str1 = 1
            }

            "02" -> {
                str1 = 2
            }

            "03" -> {
                str1 = 3
            }

            "04" -> {
                str1 = 4
            }

            "05" -> {
                str1 = 5
            }

            "06" -> {
                str1 = 6
            }

            "07" -> {
                str1 = 7
            }

            "08" -> {
                str1 = 8
            }

            "09" -> {
                str1 = 9
            }

            else -> {
                str1 = month.toInt()
            }
        }
        return str1
    }

    private fun setINt2(month: Int): String {
        var str1 = ""
        when (month) {
            1 -> {
                str1 = "01"
            }

            2 -> {
                str1 = "02"
            }

            3 -> {
                str1 = "03"
            }

            4 -> {
                str1 = "04"
            }

            5 -> {
                str1 = "05"
            }

            6 -> {
                str1 = "06"
            }

            7 -> {
                str1 = "07"
            }

            8 -> {
                str1 = "08"
            }

            9 -> {
                str1 = "09"
            }

            else -> {
                str1 = month.toString()
            }
        }
        return str1
    }

    var layoutPosition2 = 0
    var isJt = 0
    fun setZc(layoutPosition: Int, position: Int, str: String) {

        layoutPosition2 = layoutPosition
        val curDate = Date(System.currentTimeMillis())
        val tim2 = getTime2(curDate)
        var arr = str.split("-")
        var str5 = setINt2(arr[2].toInt())
        var time8 = "${arr[0]}-${arr[1]}-$str5"
        Log.e("tim2", tim2)
        Log.e("tim2", time8)
        if (tim2 == time8) {
            isJt = 0
        } else {
            isJt = 1
        }
        vm.getMasterServiceTime(str, cate_id)
        service_day = str
        for (b in list) {
            for (b2 in b.timeList) {
                b2.isCheck = 0
            }
        }
        list[layoutPosition].timeList[position].isCheck = 1
        for (b in list) {
            b.isCheck = 0
        }

        adapter.notifyDataSetChanged()
    }

    fun MyTime(serviceTime: String) {
        service_time = serviceTime
    }

}